package com.xxl.job.admin.controller;

import com.alibaba.fastjson.JSON;
import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.service.JawsJobGovernService;
import com.xxl.job.admin.vo.OpResponse;
import com.xxl.job.core.biz.model.ReturnT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * jaws 基于xxl job 扩展web接口
 *
 * @author liangqm
 * @date 2018/7/23 8:25
 * @since v1.0.0
 */
@Controller
@RequestMapping("/jobGovern")
public class JawsJobGovernController {

	private static Logger logger = LoggerFactory.getLogger(JobGroupController.class);

	@Resource
	private JawsJobGovernService jawsJobGovernService;

	@RequestMapping("/obtainJobExecutorId")
	@ResponseBody
	public OpResponse obtainJobExecutorId(XxlJobGroup xxlJobGroup) {
		logger.info("obtainJobExecutorId xxlJobGroup ==> {}", xxlJobGroup);
		OpResponse opResponse = OpResponse.success();
		Integer groupId;
		try {
			groupId = jawsJobGovernService.obtainJobExecutorId(xxlJobGroup);
			logger.info("{} group id ==> {}", xxlJobGroup.getAppName(), groupId);
			opResponse.setContent(groupId);
		} catch (Exception e) {
			return OpResponse.fail(-1, JSON.toJSONString(e), "");
		}
		return opResponse;
	}


	@RequestMapping("/registerJob")
	@ResponseBody
	public OpResponse registerJob(XxlJobInfo xxlJobInfo) {
		logger.info("registerJob xxlJobInfo ==> {}", xxlJobInfo);
		OpResponse opResponse = OpResponse.success();

		try {
			xxlJobInfo = jawsJobGovernService.registerJob(xxlJobInfo);
			opResponse.setContent(xxlJobInfo);
		} catch (Exception e) {
			return OpResponse.fail(-1, JSON.toJSONString(e), "");
		}

		return opResponse;
	}
}
